<template>
	<view class="warp">
		<!-- #ifdef APP -->
		<statusBar></statusBar>
		<!-- #endif -->
		
		<!-- 加载中遮罩层 -->
		<view class="loading-mask" v-if="isLoading">
			<view class="loading-content">
				<uni-icons type="spinner-cycle" size="30" color="#4CAF50"></uni-icons>
				<text class="loading-text">加载中...</text>
			</view>
		</view>
		
		<!-- 开台遮罩层 -->
		<view class="table-mask" v-if="showMask">
			<view class="mask-content">
				<uni-icons type="spinner-cycle" size="30" color="#4CAF50"></uni-icons>
				<text class="mask-text">开台中...</text>
			</view>
		</view>
		
		<!-- 台球桌列表 -->
		<view class="table-list" :class="{'table-list-disabled': isLoading}">
			<view class="table-item" v-for="(item, index) in tableList" :key="index" @click="handleTableClick(item)">
				<view class="table-content" :class="{'table-active': item.status === 'using'}">
					<view class="table-name-center">
						<text class="table-number">{{item.name}}</text>
					</view>
					<view class="table-info">
						<text class="table-status" :class="{'status-active': item.status === 'using'}">
							{{item.status === 'using' ? '使用中' : '空闲'}}
						</text>
					</view>
					<button class="action-btn" :class="{'btn-active': item.status === 'using'}" @click.stop="toggleTableStatus(item)">
						{{item.status === 'using' ? '关台' : '开台'}}
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	// #ifdef APP
	import statusBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-status-bar";
	// #endif
	import { store } from '@/uni_modules/uni-id-pages/common/store.js'
	
	export default {
		// #ifdef APP
		components: {
			statusBar
		},
		// #endif
		data() {
			return {
				tableList: [
					{ name: '1号台', status: 'free' },
					{ name: '2号台', status: 'free' },
					{ name: '3号台', status: 'free' },
					{ name: '4号台', status: 'free' },
					{ name: '5号台', status: 'free' },
					{ name: '6号台', status: 'free' }
				],
				hourlyRate: 0, // 每小时费率
				userInfo: null, // 用户信息
				isLoading: true, // 加载状态
				showMask: false // 开台遮罩层状态
			}
		},
		computed: {
			hasLogin() {
				return store.hasLogin
			}
		},
		async onLoad() {
			this.isLoading = true
			try {
				// 获取台球计费费率
				const db = uniCloud.database()
				const rateRes = await db.collection('yijia-xitongpeizhi').where({
					key: 'taiqiujifei'
				}).get()
				
				if (rateRes.result.data && rateRes.result.data.length > 0) {
					this.hourlyRate = parseFloat(rateRes.result.data[0].value)
				}
				
				// 获取用户信息
				if (this.hasLogin) {
					this.userInfo = store.userInfo
				}

				// 获取台球桌使用状态
				await this.getTableStatus()
			} catch (e) {
				console.error('初始化数据失败：', e)
				uni.showToast({
					title: '加载数据失败',
					icon: 'error'
				})
			} finally {
				this.isLoading = false
			}
		},
		methods: {
			// 获取台球桌使用状态
			async getTableStatus() {
				const db = uniCloud.database()
				try {
					// 获取所有正在使用的台球桌
					const usageRes = await db.collection('yijia-taiqiu-usage')
						.where({
							status: 'using'
						})
						.get()

					// 更新台球桌状态
					if (usageRes.result.data) {
						const usingTables = usageRes.result.data
						this.tableList = this.tableList.map(table => {
							const isUsing = usingTables.some(usage => usage.table_id === table.name)
							return {
								...table,
								status: isUsing ? 'using' : 'free'
							}
						})
					}
				} catch (e) {
					console.error('获取台球桌状态失败：', e)
					uni.showToast({
						title: '获取台球桌状态失败',
						icon: 'error'
					})
				}
			},
			handleTableClick(item) {
				// 点击台球桌的处理逻辑
			},
			async toggleTableStatus(item) {
				// 检查是否登录
				if (!this.hasLogin) {
					uni.showModal({
						title: '提示',
						content: '请先登录后再操作',
						confirmText: '去登录',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
								})
							}
						}
					})
					return
				}
				
				if (item.status === 'free') {
					// 开台
					this.showMask = true // 显示遮罩层
					try {
						const result = await uniCloud.callFunction({
							name: 'yijia-jiefei',
							data: {
								action: 'start',
								table_id: item.name,
								user_id: this.userInfo._id,
								user_name: this.userInfo.nickname || this.userInfo.username
							}
						})
						
						if (result.result.code === 200) {
							item.status = 'using'
							uni.showToast({
								title: '开台成功',
								icon: 'success'
							})
						} else {
							throw new Error(result.result.message)
						}
					} catch (e) {
						uni.showToast({
							title: e.message || '开台失败',
							icon: 'error'
						})
					} finally {
						this.showMask = false // 关闭遮罩层
					}
				} else {
					// 关台
					try {
						const result = await uniCloud.callFunction({
							name: 'yijia-jiefei',
							data: {
								action: 'end',
								table_id: item.name,
								user_id: this.userInfo._id
							}
						})
						
						if (result.result.code === 200) {
							item.status = 'free'
							const { minutes, billableMinutes, totalAmount } = result.result.data
							uni.showModal({
								title: '关台成功',
								content: `实际使用时长：${minutes}分钟\n计费时长：${billableMinutes}分钟\n费用：${totalAmount}元`,
								showCancel: false
							})
						} else {
							throw new Error(result.result.message)
						}
					} catch (e) {
						uni.showToast({
							title: e.message || '关台失败',
							icon: 'error'
						})
					}
				}
			}
		}
	}
</script>

<style>
	.warp {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-top: 20rpx;
	}
	
	.table-list {
		padding: 20rpx;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: space-between;
	}
	
	.table-item {
		width: 48%;
		margin-bottom: 20rpx;
	}
	
	.table-content {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.table-active {
		background-color: #E8F5E9;
	}
	
	.table-name-center {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 120rpx;
	}
	
	.table-info {
		margin-top: 15rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.table-number {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}
	
	.table-status {
		font-size: 24rpx;
		color: #999;
	}
	
	.status-active {
		color: #4CAF50;
	}
	
	.action-btn {
		margin-top: 15rpx;
		background-color: #4CAF50;
		color: #fff;
		font-size: 28rpx;
		padding: 10rpx 0;
		border-radius: 8rpx;
	}
	
	.btn-active {
		background-color: #f44336;
	}
	
	.table-list-disabled {
		pointer-events: none;
		opacity: 0.7;
	}
	
	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(255, 255, 255, 0.9);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}
	
	.loading-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #fff;
		padding: 30rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.loading-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #666;
	}
	
	.table-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.4);
		z-index: 999;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.mask-content {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 12rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.mask-text {
		margin-top: 20rpx;
		color: #333;
		font-size: 28rpx;
	}
</style>
